from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField, SelectField
from wtforms.validators import Length, Optional, DataRequired, ValidationError
from ...models import Category
from flask import Markup


class EditForm(FlaskForm):
    title = StringField('标题', validators=[
        Length(min=1, max=64, message='标题长度1~64之间')
    ])
    category_id = SelectField('发布栏目', coerce=int)
    content = TextAreaField('内容', validators=[
        Length(min=5, message='内容不能为空')
    ])
    author = StringField('作者', validators=[
        DataRequired(),
        Length(min=1, max=8, message='作者字长最多8')
    ])
    phone = StringField('联系方式', validators=[
        DataRequired(),
        Length(min=1, max=11, message='联系方式字长最多11')
    ])
    address  =StringField('地址', validators=[
        DataRequired(),
        Length(min=1, max=128, message='地址字长最多128')
    ])

    save = SubmitField('发表')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.category_id.choices = []
        for item in Category.html_tree():
            length = len(item.level.split('-'))
            if length == 1:
                _str = ''
            elif length == 2:
                _str = '&nbsp;&nbsp;&nbsp;'
            else:
                _str = '&nbsp;&nbsp;&nbsp;' * (length - 1)
            self.category_id.choices.append(
                (
                    item.id,
                    Markup(_str + item.mark + item.title)
                )
            )